<?php

// requires
require_once './library/config.php';
require_once LIB_PATH.'/facebook/facebook.php';
require_once LIB_PATH.'/facebook/facebookapi_php5_restlib.php';



//only do these if session_key cookie isn't set, otherwise redirect to the page after login.
if(empty($_COOKIE['facebook_session_key'])) {

	//clear cookies and send user to login page if no auth_token
	$auth_token = (isset($_GET['auth_token'])?$_GET['auth_token']:'');
	
	// no token set -> clear all cookies and go to the login page
	if ($auth_token == '') {
	  $cookiesSet = array_keys($_COOKIE);
	  for ($x=0;$x<count($cookiesSet);$x++) setcookie($cookiesSet[$x],"",time()-1);
	  header('Location: http://www.facebook.com/login.php?v=1.0&next=' . urlencode('login.php') . '&api_key=' . FB_API_KEY);
	  exit;
	}


  // Create our client object.  

  // This is a container for all of our static information.

  $client = new FacebookRestClient(FB_API_KEY, FB_API_SECRET);



	  // The required call: Establish session 
	
	  // The session key is saved in the client lib for the whole PHP instance.
	
	  $session_info = $client->auth_getSession($auth_token);
	
	  $session_key = $session_info['session_key'];
	
	  $uid = $session_info['uid'];

  

	//destroy client and set it back again with the session key

	$client = null;

	$client = new FacebookRestClient(FB_API_KEY, FB_API_SECRET, $session_key);

	

	//set the cookies

	setcookie('facebook_session_key', $session_key);

	setcookie('facebook_uid', $uid);

	

}

	//redirect to sample_client.php

	header('Location: index.php');

?>
